package com.chase.champagne.utils

import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.os.Build
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import java.io.PrintWriter
import java.io.StringWriter
import android.view.ViewGroup
import android.R.color
import android.provider.Settings
import android.view.WindowManager
import androidx.core.content.ContextCompat
import com.chase.champagne.R
//import net.sourceforge.pinyin4j.PinyinHelper
//import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
//import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
//import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import org.litepal.tablemanager.typechange.BooleanOrm


fun Context.showToast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) =
    Toast.makeText(this, text, duration).show()

fun Context.showAlert(
    message: String,
    positive: String,
    negative: String,
    positiveAction: (dialog: DialogInterface) -> Unit = {},
    negativeAction: (dialog: DialogInterface) -> Unit = {}
) {
    val dialogOnClickListener = DialogInterface.OnClickListener { dialog, which ->
        when (which) {
            Dialog.BUTTON_POSITIVE -> positiveAction(dialog)
            Dialog.BUTTON_NEGATIVE -> negativeAction(dialog)
        }
    }
    val alertBuilder = AlertDialog.Builder(this)
    alertBuilder.setMessage(message)
    alertBuilder.setPositiveButton(positive, dialogOnClickListener)
    alertBuilder.setNegativeButton(negative, dialogOnClickListener)
    alertBuilder.create().show()
}

fun logd(message: String, functionName: String = "", contextName: String = "") =
    Log.d("GSC-$functionName-$contextName", message)

/**
 * 将data复制到系统剪贴板上
 * Copy the data into clipboard
 * @param context context
 * @param data the data for coping into clipboard
 */
fun copy2Clipboard(context: Context, data: String) {
    val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    // Set data into clipboard
    // clipboard.primaryClip = ClipData.newPlainText(null, data)
    clipboard.setPrimaryClip(ClipData.newPlainText(null, data))
}

/**
 * 获取异常内容
 * Get content in Exception
 * @return String the content of Exception
 */
fun Exception.getContent(): String {
    val sw = StringWriter()
    val pw = PrintWriter(sw, true)
    this.printStackTrace(pw)
    pw.flush()
    sw.flush()
    return sw.toString()
}

fun Activity.useDarkStatusBar() {
    // 设置状态栏字体颜色为黑色
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val window = this.window
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }
}

private const val MIUI_FULLSCREEN_GESTURE = "force_fsg_nav_bar"

fun isMIUINavigationGestureEnabled(context: Context): Boolean {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Settings.Global.getInt(context.contentResolver, MIUI_FULLSCREEN_GESTURE, 0) != 0
    } else {
        false
    }
}

fun Activity.useImmersingNavigator(
    lightStatusBar: Boolean = true,
    navigationBarColor: Int
) {
    if (!isMIUINavigationGestureEnabled(this)) {
        // 未开启全面屏手势，不沉浸
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 设置导航栏颜色
            window.navigationBarColor = navigationBarColor
            // 设置导航栏分割线为透明
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                window.navigationBarDividerColor = Color.TRANSPARENT
            }
            // 设置导航栏、状态栏图标颜色为黑色
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (!lightStatusBar) {
                    this.window.decorView.systemUiVisibility =
                        (View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR)
                } else {
                    this.window.decorView.systemUiVisibility =
                        (View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR
                                or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
                }
            }
        }
        return
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (!lightStatusBar) {
            this.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        } else {
            this.window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
        }

//        val androidContainer = this.findViewById(android.R.id.content) as ViewGroup
//        val contentView = androidContainer.getChildAt(0)
//        contentView?.let {
//            it.layoutParams.height = getStatusBarHeight(this)
//        }

//        val androidContainer = this.findViewById(android.R.id.content) as ViewGroup
//        val contentView = androidContainer.getChildAt(1)
//        contentView?.let {
//            it.layoutParams.height = it.layoutParams.height + getStatusBarHeight(this)
//        }

//        //透明状态栏
////        this.window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
//        val androidContainer = this.findViewById(android.R.id.content) as ViewGroup
//        // 留出高度 setFitsSystemWindows  true代表会调整布局，会把状态栏的高度留出来
////        val contentView = androidContainer.getChildAt(0)
////        if (contentView != null) {
////            contentView.fitsSystemWindows = true
////        }
//        // 在原来的位置上添加一个状态栏
//        val statusBarView = createStatusBarView(this)
//        statusBarView.setBackgroundColor(Color.BLUE)
//        androidContainer.addView(statusBarView, 1)
    }
}

/**
 * 创建一个需要填充statusBarView
 */
private fun createStatusBarView(activity: Activity): View {
    val statusBarView = View(activity)
    val statusBarParams = ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)
    )
    statusBarView.layoutParams = statusBarParams
    return statusBarView
}

/**
 * 获取状态栏的高度
 * Get status bar height
 * @param context
 * @return Int the height of status bar
 */
fun getStatusBarHeight(context: Context): Int {
    var result = 0
    val resourceId = context.resources.getIdentifier("status_bar_height", "dimen", "android")
    if (resourceId > 0) {
        result = context.resources.getDimensionPixelSize(resourceId)
    }
    return result
}

/**
 * 根据设备的分辨率将dp转成为px(像素)
 * Transform dp into px according to resolution ratio of device
 * @param context
 * @param dipValue
 * @return Int px value
 */
fun dp2px(context: Context?, dipValue: Float): Int {
    if (context != null) {
//        if (WindowManager.LayoutParams.FILL_PARENT as Float == dipValue) {
//            return WindowManager.LayoutParams.FILL_PARENT
//        }
//        if (WindowManager.LayoutParams.WRAP_CONTENT as Float == dipValue) {
//            return WindowManager.LayoutParams.WRAP_CONTENT
//        }
        val scale = context.resources.displayMetrics.density
        return (dipValue * scale + 0.5f).toInt()
    }
    return dipValue.toInt()
}

/**
 * 根据设备的分辨率将px(像素)的单位转成为dp
 * Transform px into dp according to resolution ratio of device
 * @param context
 * @param pxValue
 * @return Int dp value
 */
fun px2dp(context: Context, pxValue: Float): Int {
    val scale = context.resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

// https://blog.csdn.net/qq_39089503/article/details/82288333
//fun getFirstSpell(name: String): String {
//    fun codeType(ch: Char): Int {
//        return when {
//            ch in '\u4e00'..'\u9fa5' -> 1 // Chinese
//            ch in '\u0030'..'\u0039' -> 2 // Number
//            (ch in '\u0041'..'\u005A') or (ch in '\u0061'..'\u007A') -> 3 // English
//            else -> 0
//        }
//    }
//
//    val arr: CharArray = name.toCharArray()
//    val format = HanyuPinyinOutputFormat()
//    format.caseType = HanyuPinyinCaseType.UPPERCASE
//    format.toneType = HanyuPinyinToneType.WITHOUT_TONE
//    return when (codeType(arr[0])) {
//        1 -> {
//            val charArr = PinyinHelper.toHanyuPinyinStringArray(arr[0], format)[0].toCharArray()
//            charArr[0].toString()
//        }
//        3 -> {
//            arr[0].toString().toUpperCase()
//        }
//        else -> arr[0].toString()
//    }
//}